package com.example.xgsweather.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.xgsweather.R;
import com.example.xgsweather.activity.ManageCitiesActivity;
import com.example.xgsweather.activity.MoreActivity;
import com.example.xgsweather.util.HttpUtil;
import com.example.xgsweather.util.LogUtil;
import com.qweather.sdk.bean.IndicesBean;
import com.qweather.sdk.bean.air.AirNowBean;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.IndicesType;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.weather.WeatherDailyBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherFragment extends Fragment {
    private static final String TAG = "WeatherFragment:";

    /**
     * 当前城市的天气id
     */
    public String mWeatherId;
    /**
     * 当前城市的名字
     */
    public String mCountyName;
    /**
     * 滑动菜单（切换城市）
     */
    public DrawerLayout drawerLayout;
    /**
     * 下拉刷新
     */
    public SwipeRefreshLayout swipeRefresh;
    /**
     * 显示滑动菜单的按钮
     */
    private Button navButton;
    /**
     * 显示弹出菜单的按钮
     */
    private Button menuButton;
    /**
     * 背景图片
     */
    private ImageView bingPicImg;
    /**
     * 天气页面的滚动控件
     */
    private ScrollView weatherLayout;
    /**
     * 当前城市名字
     */
    private TextView titleCity;
    /**
     * 上次更新时间
     */
    private TextView titleUpdateTime;
    /**
     * 当前气温
     */
    private TextView degreeText;
    /**
     * 当前天气
     */
    private TextView weatherInfoText;
    /**
     * 未来几天天气信息
     */
    private LinearLayout forecastLayout;
    /**
     * 更多天气信息网页链接
     */
    private LinearLayout moreLayout;
    /**
     * 空气质量
     */
    private TextView qltyText;
    /**
     * AQI（空气质量）指数
     */
    private TextView aqiText;
    /**
     * PM2.5指数
     */
    private TextView pm25Text;
    /**
     * 舒适度
     */
    private TextView comfortText;
    /**
     * 洗车指数
     */
    private TextView carWashText;
    /**
     * 运动建议
     */
    private TextView sportText;

    public String getDegree() {
        return degree;
    }

    public String getWeatherInfo() {
        return weatherInfo;
    }

    private String degree = "";
    private String weatherInfo = "";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            this.mWeatherId = getArguments().getString("weather_id");
            this.mCountyName = getArguments().getString("county_name");
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_weather, container, false);
        // 初始化各控件
        drawerLayout = view.findViewById(R.id.drawer_layout);
        navButton = view.findViewById(R.id.nav_button);
        menuButton = view.findViewById(R.id.menu_button);
        swipeRefresh = view.findViewById(R.id.swipe_refresh);
        weatherLayout = view.findViewById(R.id.weather_layout);
        titleCity = view.findViewById(R.id.title_city);
        titleUpdateTime = view.findViewById(R.id.title_update_time);
        degreeText = view.findViewById(R.id.degree_text);
        weatherInfoText = view.findViewById(R.id.weather_info_text);
        forecastLayout = view.findViewById(R.id.forecast_layout);
        moreLayout = view.findViewById(R.id.forecast_more);
        qltyText = view.findViewById(R.id.qlty_text);
        aqiText = view.findViewById(R.id.aqi_text);
        pm25Text = view.findViewById(R.id.pm25_text);
        comfortText = view.findViewById(R.id.comfort_text);
        carWashText = view.findViewById(R.id.car_wash_text);
        sportText = view.findViewById(R.id.sport_text);
        bingPicImg = view.findViewById(R.id.bing_pic_img);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadBingPic();
        // 请求数据的时候先将ScrollView进行隐藏（不然空数据的界面看上去会很奇怪）。
        weatherLayout.setVisibility(View.INVISIBLE);
        requestWeatherForQWeather(mWeatherId);
        // 设置下拉刷新进度条颜色
        swipeRefresh.setColorSchemeResources(R.color.teal_200);

        swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestWeatherForQWeather(mWeatherId);
            }
        });
        navButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开滑动菜单
                drawerLayout.openDrawer(GravityCompat.START);
            }
        });
        menuButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindowMenu(v);
            }
        });
    }

    private void showPopupWindowMenu(View view) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.item_popup_menu, null);
        float scale = getResources().getDisplayMetrics().density;
        int width = (int) (160 * scale + 0.5f);
        int height = (int) (50 * scale + 0.5f);
        PopupWindow popupWindow = new PopupWindow(contentView, width, height, true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setElevation(15);
        int[] location = new int[2];
        view.getLocationOnScreen(location);
        popupWindow.showAtLocation(view, Gravity.NO_GRAVITY, location[0] - 255, location[1]);

        TextView actionManageCities = contentView.findViewById(R.id.action_manage_cities);
        actionManageCities.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                Intent intent1 = new Intent(getActivity(), ManageCitiesActivity.class);
                startActivity(intent1);
                getActivity().finish();
            }
        });

        // TODO: 2023/6/7 添加一个设置，是否在通知栏显示天气
        TextView actionSettings = contentView.findViewById(R.id.action_weather_settings);
        actionSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                /*Intent intent1 = new Intent(getActivity(), SettingsActivity.class);
                startActivity(intent1);
                getActivity().finish();*/
            }
        });

    }

    /*
     * 根据天气id请求城市天气信息
     */
    public void requestWeatherForQWeather(String location) {
        LogUtil.w(TAG + "requestWeatherForQWeather()（刷新天气）：" + mCountyName + "：" + location);
        // 查询当前天气
        QWeather.getWeatherNow(getActivity().getApplicationContext(), location, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getWeather onError: " + e);
            }

            @Override
            public void onSuccess(WeatherNowBean weatherBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherBean.getCode()) {
                    WeatherNowBean.NowBaseBean now = weatherBean.getNow();
                    showWeatherInfo(now);
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherBean.getCode();
                    LogUtil.w(TAG + "WeatherActivity failed code: " + code);
                }
            }
        });
    }

    /*
     * 根据天气id获取城市天气预报信息
     */
    private void requestDailyForQWeather(String location) {
        // 查询天气预报
        QWeather.getWeather7D(getActivity().getApplicationContext(), location, new QWeather.OnResultWeatherDailyListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getWeatherDaily onError: " + e);
            }

            @Override
            public void onSuccess(WeatherDailyBean weatherDailyBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == weatherDailyBean.getCode()) {
                    List<WeatherDailyBean.DailyBean> dailyBeanList = weatherDailyBean.getDaily();
                    showDailyInfo(dailyBeanList);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            moreLayout.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(getActivity(), MoreActivity.class);
                                    intent.putExtra("weather_url", weatherDailyBean.getBasic().getFxLink());
                                    startActivity(intent);
                                }
                            });
                        }
                    });
                } else {
                    //在此查看返回数据失败的原因
                    Code code = weatherDailyBean.getCode();
                    LogUtil.w(TAG + " failed code: " + code);
                }
            }
        });
    }

    /*
     * 根据天气id请求城市空气质量信息
     */
    private void requestAirForQWeather(String location) {
        // 查询当前空气质量
        QWeather.getAirNow(getActivity().getApplicationContext(), location, Lang.ZH_HANS, new QWeather.OnResultAirNowListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getAir onError: " + e);
            }

            @Override
            public void onSuccess(AirNowBean airNowBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == airNowBean.getCode()) {
                    AirNowBean.NowBean now = airNowBean.getNow();
                    showAirInfo(now);
                } else {
                    //在此查看返回数据失败的原因
                    Code code = airNowBean.getCode();
                    LogUtil.w(TAG + " failed code: " + code);
                }
            }
        });
    }

    /*
     * 根据天气id请求城市生活指数信息
     */
    private void requestIndicesForQWeather(String location) {
        List<IndicesType> indicesTypes = new ArrayList<>();
        indicesTypes.add(IndicesType.COMF);
        indicesTypes.add(IndicesType.CW);
        indicesTypes.add(IndicesType.SPT);
        // 查询生活指数
        QWeather.getIndices1D(getActivity().getApplicationContext(), location, Lang.ZH_HANS, indicesTypes, new QWeather.OnResultIndicesListener() {
            @Override
            public void onError(Throwable e) {
                LogUtil.w(TAG + " getIndices1D onError: " + e);
            }

            @Override
            public void onSuccess(IndicesBean indicesBean) {
                //先判断返回的status是否正确，当status正确时获取数据，若status不正确，可查看status对应的Code值找到原因
                if (Code.OK == indicesBean.getCode()) {
                    List<IndicesBean.DailyBean> dailyBeanList = indicesBean.getDailyList();
                    showIndicesInfo(dailyBeanList);
                } else {
                    //在此查看返回数据失败的原因
                    Code code = indicesBean.getCode();
                    LogUtil.w(TAG + " failed code: " + code);
                }
            }
        });
    }

    private void showWeatherInfo(WeatherNowBean.NowBaseBean now) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String cityName = mCountyName;

                String time = now.getObsTime().substring(0, 10) + " " + now.getObsTime().substring(11, 16);
                String updateTime = "更新时间：" + time;
                degree = now.getTemp() + "℃";
                weatherInfo = now.getText();

                titleCity.setText(cityName);
                titleUpdateTime.setText(updateTime);
                degreeText.setText(degree);
                weatherInfoText.setText(weatherInfo);

                requestDailyForQWeather(mWeatherId);
            }
        });
    }

    private void showDailyInfo(List<WeatherDailyBean.DailyBean> dailyBeanList) {
        getActivity().runOnUiThread(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                // 先清除之前的预报视图内容
                forecastLayout.removeAllViews();
                for (WeatherDailyBean.DailyBean dailyBean : dailyBeanList) {
                    View view = LayoutInflater.from(getActivity()).inflate(R.layout.forecast_item, forecastLayout, false);
                    TextView dateText = view.findViewById(R.id.date_text);
                    TextView infoText = view.findViewById(R.id.info_text);
                    TextView maxText = view.findViewById(R.id.max_text);
                    TextView minText = view.findViewById(R.id.min_text);
                    dateText.setText(dailyBean.getFxDate());
                    infoText.setText(dailyBean.getTextDay());
                    maxText.setText(dailyBean.getTempMax() + "℃");
                    minText.setText(dailyBean.getTempMin() + "℃");
                    forecastLayout.addView(view);
                }
                requestAirForQWeather(mWeatherId);
            }
        });
    }

    private void showAirInfo(AirNowBean.NowBean now) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                qltyText.setText(now.getCategory());
                aqiText.setText(now.getAqi());
                pm25Text.setText(now.getPm2p5());

                requestIndicesForQWeather(mWeatherId);
            }
        });
    }

    private void showIndicesInfo(List<IndicesBean.DailyBean> dailyBeanList) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String comfort = dailyBeanList.get(0).getName() + "：" + dailyBeanList.get(0).getCategory() + "。" + dailyBeanList.get(0).getText();
                String carWash = dailyBeanList.get(1).getName() + "：" + dailyBeanList.get(1).getCategory() + "。" + dailyBeanList.get(1).getText();
                String sport = dailyBeanList.get(2).getName() + "：" + dailyBeanList.get(2).getCategory() + "。" + dailyBeanList.get(2).getText();
                comfortText.setText(comfort);
                carWashText.setText(carWash);
                sportText.setText(sport);

                weatherLayout.setVisibility(View.VISIBLE);
                // 用于表示刷新事件结束，并隐藏刷新进度条
                swipeRefresh.setRefreshing(false);
                loadBingPic();
            }
        });
    }

    /**
     * 加载必应每日一图
     */
    private void loadBingPic() {
        HttpUtil.sendOkHttpRequest(HttpUtil.requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("htest WeatherFragment", "onFailure e = " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = response.body().byteStream();
                Bitmap bitmap = BitmapFactory.decodeStream(is);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.w("htest WeatherFragment", "run: setImageBitmap");
                        bingPicImg.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }

}
